package com.chuangke.admin.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.chuangke.admin.dao.SysDataPermissionDaoService;
import com.chuangke.admin.data.builder.DeptDataBuilder;
import com.chuangke.admin.data.builder.UserDataBuilder;
import com.chuangke.admin.dto.DataPermissionRequest;
import com.chuangke.admin.entity.SysDataPermission;
import com.chuangke.admin.service.SysDataPermissionService;
import com.chuangke.common.constant.CacheKeyConstants;
import com.chuangke.common.constant.SysDataPermissionConstants;
import com.chuangke.common.data.builder.DataBuildConfig;
import com.chuangke.common.data.builder.DataBuilder;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysDataPermissionServiceImpl implements SysDataPermissionService {

	@Autowired
	private SysDataPermissionDaoService sysDataPermissionDaoService;

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_DATA_PERMISSION, key = "'" + CacheKeyConstants.SYS_DATA_PERMISSION + "'")
	@Override
	@Transactional(rollbackFor = Throwable.class)
	public void save(DataPermissionRequest dpr) {
		// 这种删除的前提条件是masterId一致
		this.delete(dpr);

		if (CollectionUtils.isEmpty(dpr.getDatas())) {
			return;
		}

		sysDataPermissionDaoService.saveBatch(dpr.getDatas());
	}

	@CacheEvict(cacheNames = CacheKeyConstants.SYS_DATA_PERMISSION, key = "'" + CacheKeyConstants.SYS_DATA_PERMISSION + "'")
	@Override
	public void delete(DataPermissionRequest dpr) {
		QueryWrapper<SysDataPermission> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(SysDataPermission::getType, dpr.getType());
		if (!StrUtil.isBlank(dpr.getMaster1Id())) {
			queryWrapper.lambda().eq(SysDataPermission::getMaster1Id, dpr.getMaster1Id());
		}
		if (!StrUtil.isBlank(dpr.getMaster2Id())) {
			queryWrapper.lambda().eq(SysDataPermission::getMaster2Id, dpr.getMaster2Id());
		}
		if (!StrUtil.isBlank(dpr.getMaster3Id())) {
			queryWrapper.lambda().eq(SysDataPermission::getMaster3Id, dpr.getMaster3Id());
		}
		if (!StrUtil.isBlank(dpr.getMaster4Id())) {
			queryWrapper.lambda().eq(SysDataPermission::getMaster4Id, dpr.getMaster4Id());
		}
		if (!StrUtil.isBlank(dpr.getMaster5Id())) {
			queryWrapper.lambda().eq(SysDataPermission::getMaster5Id, dpr.getMaster5Id());
		}
		sysDataPermissionDaoService.remove(queryWrapper);
	}
	
	@CacheEvict(cacheNames = CacheKeyConstants.SYS_DATA_PERMISSION, key = "'" + CacheKeyConstants.SYS_DATA_PERMISSION + "'")
	@Override
	public void removeByIds(List<String> ids) {
		sysDataPermissionDaoService.removeBatchByIds(ids) ;
	}

	/**
	 * key为type
	 */
	@Cacheable(cacheNames = CacheKeyConstants.SYS_DATA_PERMISSION, key = "'" + CacheKeyConstants.SYS_DATA_PERMISSION + "'")
	@Override
	public Map<String, List<SysDataPermission>> findAll() {
		List<SysDataPermission> list = sysDataPermissionDaoService.list();
		return list.stream().collect(Collectors.groupingBy(SysDataPermission::getType));
	}

	@Override
	public List<SysDataPermission> find(String type) {
		Map<String, List<SysDataPermission>> map = ((SysDataPermissionService) AopContext.currentProxy()).findAll();
		map = map == null ? new HashMap<>() : map;
		List<SysDataPermission> list = map.getOrDefault(type,new ArrayList<>());
		bindName(list) ;
		return list;
	}

	@Override
	public List<SysDataPermission> find(DataPermissionRequest dpr) {
		List<SysDataPermission> list = ((SysDataPermissionService) AopContext.currentProxy()).find(dpr.getType());

		list = list.stream().filter(sdp -> {
			if (!StrUtil.isBlank(dpr.getMaster1Id()) && !StringUtils.equals(sdp.getMaster1Id(), dpr.getMaster1Id())) {
				return false;
			}
			if (!StrUtil.isBlank(dpr.getMaster2Id()) &&!StringUtils.equals(sdp.getMaster2Id(), dpr.getMaster2Id())) {
				return false;
			}
			if (!StrUtil.isBlank(dpr.getMaster3Id()) &&!StringUtils.equals(sdp.getMaster3Id(), dpr.getMaster3Id())) {
				return false;
			}
			if (!StrUtil.isBlank(dpr.getMaster4Id()) &&!StringUtils.equals(sdp.getMaster4Id(), dpr.getMaster4Id())) {
				return false;
			}
            return StrUtil.isBlank(dpr.getMaster5Id()) || StringUtils.equals(sdp.getMaster5Id(), dpr.getMaster5Id());
        }).collect(Collectors.toList());

		return list;
	}

	private void bindName(List<SysDataPermission> list) {
		if(CollectionUtils.isEmpty(list)){
			return ;
		}

		DataBuilder.of(list).appendBuilder(new UserDataBuilder(), new DataBuildConfig("createdBy", "createdByName"),
				new DataBuildConfig("updatedBy", "updatedByName")).build();

		if(SysDataPermissionConstants.TYPE_USER_DUTY.equals(list.get(0).getType())) {
			DataBuilder.of(list)
					.appendBuilder(new DeptDataBuilder(), new DataBuildConfig("dataId", "dataName")).build();
		}
	}

}
